package com.emex.app.stuff.gui;

import com.emex.app.shared.data.OrderPayment;
import com.emex.app.shared.data.OrderPosition;
import com.emex.app.shared.data.Orders;
import com.emex.app.shared.data.Position;
import com.emex.app.shared.data.enums.OrderPositionStatus;
import com.emex.app.shared.data.enums.OrderStatus;
import com.emex.app.shared.data.enums.PayMethod;
import com.emex.app.stuff.constant.IdentifierConstants;
import com.emex.app.stuff.constant.ReportName;
import com.emex.app.stuff.gui.model.ConfirmedPositionsTableModel;
import com.emex.app.stuff.provider.OrderDataProvider;
import com.emex.app.stuff.provider.ShopDataProvider;
import com.emex.app.stuff.security.SecurityManager;
import com.emex.app.stuff.utils.DateUtils;
import com.emex.app.stuff.utils.ReportGenerator;
import com.emex.app.stuff.utils.UIUtils;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRMapArrayDataSource;
import org.openide.util.Exceptions;
import org.openide.windows.WindowManager;

/**
 *
 * @author Sergey Karavaev
 */
public class ConfirmPositionDialog extends javax.swing.JDialog {

    private ConfirmedPositionsTableModel confirmedPositionsTableModel;

    private List<Position> positions;

    /**
     * Creates new form ConfirmPositionDialog
     */
    public ConfirmPositionDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        payMethod.setModel(new DefaultComboBoxModel(PayMethod.values()));
    }

    public List<Position> getPositions() {
        return positions;
    }

    public void setPositions(Set<Position> positions) {
        if (null != positions) {
            this.positions = new ArrayList<>();
            this.positions.addAll(positions);
            for (Position p : this.positions) {
                p.setMinAmount(p.getAmount());
                p.setAmount(1);
            }
            confirmedPositionsTableModel = new ConfirmedPositionsTableModel(this.positions);
            positionsTable.setModel(confirmedPositionsTableModel);
            positionsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    int row = positionsTable.getSelectedRow();
                    if ((row >= 0) && (row < positionsTable.getRowCount())) {
                        deletePositionButton.setEnabled(true);
                    } else {
                        deletePositionButton.setEnabled(false);
                    }
                }
            });
            if (positionsTable.getRowCount() > 0) {
                printBillButton.setEnabled(true);
                saveOrderButton.setEnabled(true);
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        positionsTable = new org.jdesktop.swingx.JXTable();
        cancelButton = new javax.swing.JButton();
        saveOrderButton = new javax.swing.JButton();
        printBillButton = new javax.swing.JButton();
        deletePositionButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        payMethod = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(ConfirmPositionDialog.class, "ConfirmPositionDialog.title")); // NOI18N

        positionsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                positionsTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(positionsTable);

        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(ConfirmPositionDialog.class, "ConfirmPositionDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(saveOrderButton, org.openide.util.NbBundle.getMessage(ConfirmPositionDialog.class, "ConfirmPositionDialog.saveOrderButton.text")); // NOI18N
        saveOrderButton.setEnabled(false);
        saveOrderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveOrderButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(printBillButton, org.openide.util.NbBundle.getMessage(ConfirmPositionDialog.class, "ConfirmPositionDialog.printBillButton.text")); // NOI18N
        printBillButton.setEnabled(false);
        printBillButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printBillButtonActionPerformed(evt);
            }
        });

        deletePositionButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/delete.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(deletePositionButton, org.openide.util.NbBundle.getMessage(ConfirmPositionDialog.class, "ConfirmPositionDialog.deletePositionButton.text")); // NOI18N
        deletePositionButton.setEnabled(false);
        deletePositionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deletePositionButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ConfirmPositionDialog.class, "ConfirmPositionDialog.jLabel1.text")); // NOI18N

        payMethod.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(deletePositionButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(payMethod, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, Short.MAX_VALUE)
                        .addComponent(printBillButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(saveOrderButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(deletePositionButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(saveOrderButton)
                    .addComponent(printBillButton)
                    .addComponent(jLabel1)
                    .addComponent(payMethod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void printBillButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printBillButtonActionPerformed
        if (null == payMethod.getSelectedItem()) {
            UIUtils.showInfoMessage("Выберите форму оплаты");
            return;
        }
        try {
            HashMap parameters = new HashMap();
            boolean isAvtoozavod = true;
            String img;
            String tmr;
            String template;
            if (isAvtoozavod) {
                img = "logo_avtoz.jpg";
                tmr = "body.jpg";
                template = ReportName.ORDER_BILL_REPORT_AVTOZ;
            } else {
                img = "emexLogo.jpg";
                tmr = "emexTimer.png";
                template = ReportName.ORDER_BILL_REPORT;
            }
            BufferedImage image = ImageIO.read(getClass().getClassLoader().getResource(img));
            BufferedImage timer = ImageIO.read(getClass().getClassLoader().getResource(tmr));
            parameters.put("logo", image);
            parameters.put("emexTimer", timer);
            parameters.put("cur_date", DateUtils.getExtendedFormattedString(
                    new Date()));
            List<Map<String, String>> tableData = new ArrayList<>();
            Double genSumma = 0.0;
            Integer i = 1;
            for (Position op : confirmedPositionsTableModel.getPositions()) {
                Map<String, String> ordPosInfo = new HashMap<>();
                ordPosInfo.put("number", i.toString());
                ordPosInfo.put("detail_name", op.getName() + " " + op.getIssuer() + " " + op.getCode());
                ordPosInfo.put("amount", op.getAmount().toString());
                ordPosInfo.put("price", op.getPrice().toString());
                Double result = op.getPrice() * op.getAmount();
                genSumma += result;
                ordPosInfo.put("summa", result.toString());
                tableData.add(ordPosInfo);
                ++i;
            }
            parameters.put("genSumma", genSumma.toString());
            Map<String, String>[] tableDS = tableData.toArray(new HashMap[tableData.size()]);
            JRMapArrayDataSource mapDS = new JRMapArrayDataSource(tableDS);
            parameters.put("datasource", new JREmptyDataSource());
            parameters.put("dataSource", mapDS);
            JasperPrint jp = ReportGenerator.getInstance().generateReport(parameters, template);
            ReportGenerator.getInstance().showReport(jp);
            if (UIUtils.showConfirmation("Сохранить заказ в истории?") == JOptionPane.YES_OPTION) {
                saveOrderButtonActionPerformed(evt);
            }
        } catch (final Exception ex) {
            Exceptions.printStackTrace(ex);
            UIUtils.showErrorMessage("Произошли ошибки при печати товарного чека.");
        }
    }//GEN-LAST:event_printBillButtonActionPerformed

    private void deletePositionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deletePositionButtonActionPerformed
        Position toDelete = getPositionSelection();
        if (null != toDelete) {
            confirmedPositionsTableModel.dataRemoved(toDelete);
            if (positionsTable.getRowCount() == 0) {
                saveOrderButton.setEnabled(false);
                printBillButton.setEnabled(false);
            }
        }
    }//GEN-LAST:event_deletePositionButtonActionPerformed

    private void positionsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_positionsTableMouseClicked
        if (evt.getClickCount() == 2) {
            Position selected = getPositionSelection();
            SetAmountDialog panel = new SetAmountDialog(WindowManager.getDefault().getMainWindow(), true);
            panel.setLocationRelativeTo(null);
            panel.setPosition(selected);
            panel.setVisible(true);
            selected.setAmount(panel.getPosition().getAmount());
            confirmedPositionsTableModel.dataUpdated();
        }
    }//GEN-LAST:event_positionsTableMouseClicked

    private void saveOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveOrderButtonActionPerformed
        if (null == payMethod.getSelectedItem()) {
            UIUtils.showInfoMessage("Выберите форму оплаты");
            return;
        }
        Orders order = new Orders();
        order.setCarId(IdentifierConstants.SHOP_CAR_ID);
        order.setClientId(IdentifierConstants.SHOP_CLIENT_ID);
        order.setDate(new Date());
        order.setManagerId(SecurityManager.getDefault().getCurrentPerson().getId());
        order.setStatus(OrderStatus.COMPLTED.ordinal());
        order.setName("Заказ от " + DateUtils.getExtendedFormattedString(new Date()));
        List<OrderPosition> orderPositions = new ArrayList<>();
        Double genSumma = 0.0;
        for (Position soldPosition : confirmedPositionsTableModel.getPositions()) {
            Position originalToUpdate = ShopDataProvider.getInstance().getPositionById(soldPosition.getId());
            originalToUpdate.setAmount(originalToUpdate.getAmount() - soldPosition.getAmount());
            ShopDataProvider.getInstance().updatePosition(originalToUpdate);

            Double result = soldPosition.getPrice() * soldPosition.getAmount();
            genSumma += result;

            OrderPosition op = new OrderPosition();
            op.setAmount(soldPosition.getAmount());
            op.setName(soldPosition.getName() + " " + soldPosition.getIssuer() + " " + soldPosition.getCode());
            op.setPrice(soldPosition.getPrice());
            op.setPurPrice(soldPosition.getPurPrice());
            op.setStatus(OrderPositionStatus.ISSUED.ordinal());
            orderPositions.add(op);
        }

        order = OrderDataProvider.getInstance().insertOrder(order);

        for (OrderPosition orderPosition : orderPositions) {
            orderPosition.setOrderId(order.getId());
            OrderDataProvider.getInstance().insertOrderPosition(orderPosition);
        }

        OrderPayment orderPayment = new OrderPayment();
        orderPayment.setDate(new Date());
        orderPayment.setManagerId(SecurityManager.getDefault().getCurrentPerson().getId());
        orderPayment.setName("Оплата заказа от " + DateUtils.getExtendedFormattedString(new Date()));
        orderPayment.setOrderId(order.getId());
        orderPayment.setPayMethod(payMethod.getSelectedIndex());
        orderPayment.setSumma(genSumma);

        OrderDataProvider.getInstance().insertOrderPayment(orderPayment);
        setVisible(false);
    }//GEN-LAST:event_saveOrderButtonActionPerformed

    protected Position getPositionSelection() {
        if (positionsTable.getSelectedRow() > -1) {
            Position pos = (Position) positionsTable
                    .getValueAt(positionsTable.getSelectedRow(), -1);
            return pos;
        }
        return null;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton deletePositionButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox payMethod;
    private org.jdesktop.swingx.JXTable positionsTable;
    private javax.swing.JButton printBillButton;
    private javax.swing.JButton saveOrderButton;
    // End of variables declaration//GEN-END:variables
}
